package alg20241029;

import java.util.ArrayList;
import java.util.List;

public class Text2 {
    public static void main(String[] args) {
        String s = "cbaebabacd";
        String p = "abc";
        System.out.println(findAnagrams1(s, p));
    }

    public static List<Integer> findAnagrams(String ss, String pp) {
        List<Integer> ret = new ArrayList<>();
        int[] hashS = new int[128];
        int[] hashP = new int[128];
        char[] s = ss.toCharArray();
        char[] p = pp.toCharArray();
        int lenP = p.length;
        int count = 0;
        for (int i = 0; i < lenP; i++) {
            hashP[p[i]]++;
        }
        for (int left = 0, right = 0; right < s.length; right++) {
            //进窗口
            hashS[s[right]]++;
            //进窗口之后判断
            if(hashS[s[right]] <= hashP[s[right]]){
                count++;
            }
            //出窗口
            if(right - left + 1 > lenP){
                //出窗口之前判断
                if(hashS[s[left]] <= hashP[s[left]]){
                    count--;
                }
                hashS[s[left++]]--;
            }

            //更新结果
            if(count == lenP){
                ret.add(left);
            }
        }
        return ret;

    }


    public static List<Integer> findAnagrams1(String ss, String pp) {
        List<Integer> ret = new ArrayList<>();

        int[] hashS = new int[128];
        int[] hashP = new int[128];
        char[] s = ss.toCharArray();
        char[] p = pp.toCharArray();
        int lenP = p.length;
        for (int i = 0; i < lenP; i++) {
            hashP[p[i]]++;    //更新哈希表p
        }
        for (int left = 0, right = 0; right < s.length; right++) {
            //进窗口
            hashS[s[right]]++;
            //判断
            if(right - left + 1 > lenP){
                hashS[s[left++]]--;                     //出窗口
            }
            //更新结果
            boolean flg = false;
            for (int i = 'a'; i <= 122; i++) {
                if(hashS[i] != hashP[i]){
                    flg = true;
                    break;
                }
            }
            if(!flg){
                ret.add(left);
            }
        }
        return ret;
    }


}
